<script lang="ts" setup>
import {
  getPatientConsultOrderDetailAPI,
  postPatientConsultOrderAPI,
  postPatientConsultPayAPI,
} from '@/api/consult'
import { DeletePatientOrderAPI, PutCancelPatientOrderAPI } from '@/api/order'
import { useConsultStore } from '@/store/consult'
import type { GetPatientConsultOrderDetailRes } from '@/types/consult'
import type { CustomPaymentInstance } from '@/types/GlobalComponents'
import { ref } from 'vue'

// 获取订单id
const props = defineProps<{
  orderId: string
}>()

// 获取订单详情
const orderDetail = ref<GetPatientConsultOrderDetailRes>({} as GetPatientConsultOrderDetailRes)

const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI({ orderId: props.orderId })
  orderDetail.value = res
  console.log(res)
}
getOrderDetail()

// 订单类型1问医生2极速问诊3开药问诊4药品订单
const typeMap: Record<number, string> = {
  1: '图文问诊',
  2: '极速问诊',
  3: '开药问诊',
  4: '药品订单',
}

// 删除订单
const handleDeleteOrder = async () => {
  console.log('删除订单')
  await DeletePatientOrderAPI(props.orderId)
  await uni.navigateBack()
  uni.showToast({
    title: '删除成功',
    icon: 'success',
  })
}

// 取消问诊
const handleCancelOrder = async () => {
  console.log('取消问诊')
  await PutCancelPatientOrderAPI(props.orderId)
  uni.showToast({
    title: '取消成功',
    icon: 'success',
  })
  await uni.navigateBack()
}

// 去支付

const handlePayOrder = async () => {
   customPaymentRef.value?.open?.()
}

// 支付组件
const customPaymentRef = ref<CustomPaymentInstance>()

// 关闭支付
const onPaymentClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}

// 支付方式改变
const onPaymentChange = (index: number) => {
  console.log('支付方式改变', index)
}

// 确认支付
const onPaymentConfirm = async (index: number) => {
  console.log('确认支付', index)

  // 微信支付
  if (index === 0) {
    uni.showToast({
      title: '暂不支持微信支付',
      icon: 'none',
    })

    // #ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    // wx.requestPayment(传入后端返回的支付参数)
    // #endif
  }

  // 支付宝支付
  if (index === 1) {
    console.log('支付宝支付')
    // 调用支付宝支付
    const res = await postPatientConsultPayAPI({
      orderId: props.orderId,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_consult/room/room',
    })
    console.log('支付结果', res)
    location.href = res.payUrl
  }
  //
  customPaymentRef.value?.close?.()
}
</script>

<template>
  <scroll-view background-color="#f6f6f6">
    <view class="consult-page">
      <view class="page-header">
        <!-- 订单状态 -->
        <view class="order-status">
          <view class="label">
            <text class="title">{{ typeMap[orderDetail.type] }} {{ orderDetail.payment }}元</text>
            <text class="tips">
              {{ orderDetail.cancelProcess ?? '' }}
            </text>
          </view>
          <text class="status">{{ orderDetail.statusValue }}</text>
        </view>
        <!--  医生信息 -->
        <view class="consult-doctor">
          <text class="lable">服务医生信息</text>
          <view class="doctor">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <view class="doctor-info" v-if="orderDetail.docInfo">
              <view class="meta">
                <text class="name">{{ orderDetail.docInfo?.name ?? '' }}</text>
                <text class="title"
                  >{{ orderDetail.docInfo?.depName ?? '' }} |
                  {{ orderDetail.docInfo?.positionalTitles ?? '' }}</text
                >
              </view>
              <view class="meta">
                <text class="tag">{{ orderDetail.docInfo?.gradeName ?? '' }}</text>
                <text class="hospital">{{ orderDetail.docInfo?.hospitalName ?? '' }}</text>
              </view>
            </view>

            <!-- 订单未支付时,未分配医生 -->
            <view class="doctor-info" v-else>
              <view class="meta">
                <text class="name">暂未分配</text>
              </view>
            </view>

            <view class="arrow">
              <uni-icons size="18" color="#C3C3C5" type="forward" />
            </view>
          </view>
        </view>
      </view>
      <!-- 患者信息 -->
      <view class="consult-patient">
        <view class="list-title">患者资料</view>
        <uni-list :border="false">
          <uni-list-item
            title="患者信息"
            :right-text="`${orderDetail.patientInfo?.name} | ${orderDetail.patientInfo?.genderValue} | ${orderDetail.patientInfo?.age}岁`"
          />
          <uni-list-item title="病情描述" :note="orderDetail.illnessDesc" />
        </uni-list>
      </view>

      <!-- 订单信息 -->
      <view class="order-info">
        <view class="list-title">订单信息</view>
        <uni-list :border="false">
          <uni-list-item title="订单编号" :right-text="orderDetail.orderNo" />
          <uni-list-item title="创建时间" :right-text="orderDetail.createTime" />
          <uni-list-item title="取消时间" :right-text="orderDetail.cancelProcess" />
          <uni-list-item title="应付款" :right-text="orderDetail.payment?.toString()" />
          <uni-list-item title="优惠券">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderDetail.couponDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderDetail.pointDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ orderDetail.actualPayment }}</view>
            </template>
          </uni-list-item>
          <!-- <uni-list-item title="支付时间" right-text="无" />
          <uni-list-item title="支付方式" right-text="无" /> -->
        </uni-list>
      </view>

      <!-- 倒计时 -->
      <view class="notice-bar" v-if="orderDetail.countdown !== -1">
        <!-- <uni-notice-bar :text="`请在 ${orderDetail.countdown} 内完成支付，超时订单将取消`" /> -->
        <!-- 倒计时组件 -->
        <uni-countdown
          :day="0"
          :hour="0"
          :minute="0"
          :second="orderDetail.countdown"
          :show-day="false"
        />
      </view>

      <!-- 底部 -->
      <view class="toolbar">
        <template v-if="orderDetail.status === 1">
          <view class="total-amount">
            需付款: <text class="number">¥{{ orderDetail.actualPayment }}</text>
          </view>
          <view class="buttons">
            <button class="uni-button minor" @click="handleCancelOrder">取消问诊</button>
            <button class="uni-button" @click="handlePayOrder">立即支付</button>
          </view>
        </template>
        <template v-else>
          <view class="buttons">
            <view class="delete-botton" @click="handleDeleteOrder">
              <uni-icons size="24" color="#848484" type="trash" />
              <text>删除订单</text>
            </view>
            <button class="uni-button">再次购买</button>
          </view>
        </template>
      </view>
    </view>
  </scroll-view>
  <!-- 支付弹层 -->
  <custom-payment
    ref="customPaymentRef"
    :amount="orderDetail.actualPayment ?? 0"
    :order-id="orderId"
    @close="onPaymentClose"
    @change="onPaymentChange"
    @confirm="onPaymentConfirm"
  />
</template>

<style lang="scss">
@import './index.scss';
</style>
